-- @preview-file on clear

-- LevelManager.lua
-- 关卡管理器

local LevelManager = {}
LevelManager.__index = LevelManager

local LevelTileLoader = require("LevelTileLoader")
local LevelTileConfig = require("LevelTileConfig")

function LevelManager.new()
    local instance = {
        tileLoader = LevelTileLoader.new(),
        isLevelActive = false,
        levelRootNode = nil,
        playerStartPosition = nil,
        groundPlatforms = {},
        movementSystem = nil,
        currentTileRow = 5,  -- 初始在05行
        currentTileCol = 1,  -- 初始在01列
        sceneNode = nil
    }
    return setmetatable(instance, LevelManager)
end

-- 初始化关卡
function LevelManager:initialize(sceneNode, movementSystem)
    if not sceneNode then
        return false
    end
    
    self.sceneNode = sceneNode
    self.movementSystem = movementSystem
    
    -- 创建关卡根节点
    local Node = require("Node")
    self.levelRootNode = Node()
    
    -- 添加到场景
    sceneNode:addChild(self.levelRootNode)
    
    -- 设置切片加载器的场景根节点
    self.tileLoader:setSceneRoot(self.levelRootNode)
    
    -- 获取初始位置（05_01左侧出生）
    self.playerStartPosition = LevelTileConfig.getInitialPlayerPosition()
    
    -- 获取当前切片
    local currentTile = LevelTileConfig.getTileInfoByPosition(
        self.playerStartPosition.x,
        self.playerStartPosition.y
    )
    
    if currentTile then
        self.currentTileRow = currentTile.row
        self.currentTileCol = currentTile.col
    end
    
    -- 预加载初始区域
    self.tileLoader:preloadInitialArea(self.currentTileRow, self.currentTileCol)
    
    -- 创建地面平台
    self:createGroundPlatforms()
    
    self.isLevelActive = true
    
    return true
end

-- 创建地面平台
function LevelManager:createGroundPlatforms()
    -- 清理现有平台
    self.groundPlatforms = {}
    
    -- 为每个切片创建地面平台
    for row = 1, LevelTileConfig.GRID_SIZE.rows do
        for col = 1, LevelTileConfig.GRID_SIZE.cols do
            local platform = LevelTileConfig.getTileGroundPlatform(row, col)
            if platform then
                table.insert(self.groundPlatforms, platform)
            end
        end
    end
    
    -- 将地面平台添加到运动系统
    if self.movementSystem then
        -- 先清除现有的地面平台
        if self.movementSystem.groundPlatforms then
            self.movementSystem.groundPlatforms = {}
        end
        
        -- 添加所有地面平台
        for _, platform in ipairs(self.groundPlatforms) do
            self.movementSystem:addGroundPlatform(platform)
        end
    end
    
    return #self.groundPlatforms
end

-- 更新关卡（每帧调用）
function LevelManager:update(dt, playerX, playerY)
    if not self.isLevelActive then return end
    
    -- 更新切片加载器
    self.tileLoader:updateLoadQueue()
    
    -- 更新角色所在的切片
    local currentRow, currentCol = LevelTileConfig.getTileByPosition(playerX, playerY)
    
    -- 如果角色移动到了新的切片
    if currentRow ~= self.currentTileRow or currentCol ~= self.currentTileCol then
        self.currentTileRow = currentRow
        self.currentTileCol = currentCol
        
        -- 更新切片加载
        self.tileLoader:updateByPlayerPosition(playerX, playerY)
    end
    
    return true
end

-- 获取地面平台列表
function LevelManager:getGroundPlatforms()
    return self.groundPlatforms
end

-- 根据位置获取地面平台
function LevelManager:getGroundPlatformAt(x, y)
    for _, platform in ipairs(self.groundPlatforms) do
        if x >= platform.x and x <= platform.x + platform.width and
           y >= platform.y - 10 and y <= platform.y + platform.height + 10 then
            return platform
        end
    end
    return nil
end

-- 获取玩家起始位置
function LevelManager:getPlayerStartPosition()
    return self.playerStartPosition
end

-- 设置运动系统引用
function LevelManager:setMovementSystem(movementSystem)
    self.movementSystem = movementSystem
end

-- 检查位置是否可行走
function LevelManager:isWalkable(x, y)
    return self:getGroundPlatformAt(x, y) ~= nil
end

-- 获取关卡边界
function LevelManager:getLevelBounds()
    return LevelTileConfig.getLevelBounds()
end

-- 清理关卡
function LevelManager:cleanup()
    self.isLevelActive = false
    
    if self.tileLoader then
        self.tileLoader:cleanup()
    end
    
    if self.levelRootNode and self.levelRootNode.parent then
        self.levelRootNode:removeFromParent()
    end
    
    self.groundPlatforms = {}
    self.levelRootNode = nil
    self.sceneNode = nil
    self.movementSystem = nil
    
    return true
end

return LevelManager